package cn.wit.summit.chwan.ui.fragment;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.models.dto.NotifiCationMain;
import cn.wit.summit.chwan.models.response.ResponseBase;
import cn.wit.summit.chwan.retrofit.ApiUtil;
import cn.wit.summit.chwan.retrofit.MyCallback;
import cn.wit.summit.chwan.retrofit.RetrofitManager;
import cn.wit.summit.chwan.ui.activity.NoticeActivity;
import cn.wit.summit.chwan.ui.base.BaseFragment;
import cn.wit.summit.chwan.utils.AccountUtil;
import cn.wit.summit.chwan.utils.IntentUtil;
import cn.wit.summit.chwan.utils.LogUtils;
import cn.wit.summit.chwan.utils.MobileCodeUtils;
import cn.wit.summit.chwan.utils.NetWorkUtils;
import cn.wit.summit.chwan.utils.StringUtils;
import cn.wit.summit.chwan.utils.ToastUtils;
import cn.wit.summit.chwan.widgets.MessageDialog;
import cn.wit.summit.chwan.widgets.refreshLayout.SmartRefreshLayout;
import cn.wit.summit.chwan.widgets.refreshLayout.api.RefreshLayout;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;

/**
 * Created by pengsk on 2018/4/19.
 */

public class NoticeMessageFragment extends BaseFragment {

    RecyclerView recvcleView;
    SmartRefreshLayout refreshLayout;
    List<NotifiCationMain.NotificationListBean> games = new ArrayList<>();
    LayoutInflater inflater;
    Context context;
    int from;

    public FrameLayout root_content_null_ll;
    public TextView retryText;
    public ImageView retryImg;

    private RetrofitManager retrofitManager;
    private Retrofit retrofitLogin;
    private ApiUtil apiLogin;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.recyclerview_layout, container, false);
        recvcleView = view.findViewById(R.id.recyclerView);
        refreshLayout = view.findViewById(R.id.refreshLayout);

        retrofitManager = RetrofitManager.getInstance(getActivity());
        retrofitLogin = retrofitManager.getLoginRetrofit();
        apiLogin = retrofitLogin.create(ApiUtil.class);

        root_content_null_ll = (FrameLayout) view.findViewById(R.id.root_content_null_ll);
        retryText = view.findViewById(R.id.retryText);
        retryImg = view.findViewById(R.id.retryImg);
        context = getContext();
        refreshLayout.autoLoadMore();
        refreshLayout.setOnRefreshListener(new cn.wit.summit.chwan.widgets.refreshLayout.listener.OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                pn=1;
                getNotificationData();
            }
        });
        refreshLayout.setOnLoadMoreListener(new cn.wit.summit.chwan.widgets.refreshLayout.listener.OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                getNotificationData();
            }
        });
        initView();
        getNotificationData();
        return view;
    }

    public static NoticeMessageFragment newInstance() {
        Bundle args = new Bundle();
        NoticeMessageFragment fragment = new NoticeMessageFragment();
        fragment.setArguments(args);
        return fragment;
    }

    MYUpdateAdapter adapter = null;

    private void initView() {
        inflater = LayoutInflater.from(context);
        recvcleView.setLayoutManager(new LinearLayoutManager(context));
        adapter = new MYUpdateAdapter();
        //添加自定义分割线
        DividerItemDecoration divider = new DividerItemDecoration(context, DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(context, R.drawable.item_driver_h_2px));
        recvcleView.addItemDecoration(divider);
        recvcleView.setAdapter(adapter);
    }

    private int pn = 1;

    private void getNotificationData() {
        if (NetWorkUtils.isNetworkConnected(context)) {
            apiLogin.gamenotificationData(AccountUtil.getInstance().getUid(), AccountUtil.getInstance().getToken(), pn)
                    .enqueue(new MyCallback<ResponseBase<NotifiCationMain>>() {
                        @Override
                        public void onSuccess(ResponseBase<NotifiCationMain> model) {
                            NotifiCationMain data = model.getData_info();
                            if (data != null) {
                                if (data.getNotificationList()!=null&&data.getNotificationList().size()== 0) {
                                    refreshLayout.finishRefresh();
                                    refreshLayout.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
                                } else {
                                    if (pn == 1) {
                                        games.clear();
                                    }
                                    refreshLayout.finishRefresh();
                                    refreshLayout.finishLoadMore();

                                    pn+=1;
                                    List<NotifiCationMain.NotificationListBean> datas = data.getNotificationList();
                                    games.addAll(datas);
                                    adapter.notifyDataSetChanged();
                                }

                            } else {
                                refreshLayout.finishRefresh();
                                refreshLayout.finishLoadMoreWithNoMoreData();
                            }
                            if (games.size()==0){
                                root_content_null_ll.setVisibility(View.VISIBLE);
                                refreshLayout.setVisibility(View.GONE);
                                retryText.setText("暂无相关信息!");
                                retryImg.setImageResource(R.mipmap.ic_not_data);
                            }else {
                                root_content_null_ll.setVisibility(View.GONE);
                                refreshLayout.setVisibility(View.VISIBLE);

                            }
                        }

                        @Override
                        public void onFailure(int code, String msg) {
                            ToastUtils.getInstance(context).showToastSystem(msg);
                            refreshLayout.finishRefresh();
                            refreshLayout.finishLoadMoreWithNoMoreData();
                            if (code == -3) {
                                root_content_null_ll.setVisibility(View.VISIBLE);
                                refreshLayout.setVisibility(View.GONE);
                                retryImg.setImageResource(R.mipmap.ic_not_net);
                                retryText.setText("网络异常，点击屏幕重新加载");
                            }
                        }
                    });
        } else {
            root_content_null_ll.setVisibility(View.VISIBLE);
            refreshLayout.setVisibility(View.GONE);
            retryImg.setImageResource(R.mipmap.ic_not_net);
            retryText.setText("网络异常，点击屏幕重新加载");
            root_content_null_ll.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    root_content_null_ll.setVisibility(View.GONE);
                    refreshLayout.setVisibility(View.VISIBLE);
                    getNotificationData();
                }
            });
        }

    }


    class VHNotice extends RecyclerView.ViewHolder {

        RelativeLayout noticeRootRl;
        SimpleDraweeView noticeHeaderIv;
        TextView noticeContentTv;
        TextView noticeFromTv;
        TextView noticeTimeTv;
        ImageView noticeTagIv;

        public VHNotice(View itemView) {
            super(itemView);
            noticeRootRl = itemView.findViewById(R.id.noticeRootRl);
            noticeHeaderIv = itemView.findViewById(R.id.noticeHeaderIv);
            noticeContentTv = itemView.findViewById(R.id.noticeContentTv);
            noticeFromTv = itemView.findViewById(R.id.noticeFromTv);
            noticeTimeTv = itemView.findViewById(R.id.noticeTimeTv);
            noticeTagIv = itemView.findViewById(R.id.noticeTagIv);
        }
    }

    class MYUpdateAdapter extends RecyclerView.Adapter {

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

            View view = inflater.inflate(R.layout.message_list_layout, parent, false);
            VHNotice holder = new VHNotice(view);
            return holder;
        }

        public void removeItemByPosition(int po) {
            games.remove(po);
            notifyItemRemoved(po);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    notifyDataSetChanged();
                }
            }, 500);
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, final int position) {
            final VHNotice h = (VHNotice) holder;
            final NotifiCationMain.NotificationListBean bean = games.get(position);
            h.noticeHeaderIv.setImageURI(Uri.parse(bean.getCoverBigPic()));
            h.noticeContentTv.setText(bean.getTitle());
            h.noticeTimeTv.setText(bean.getAddTime());
            h.noticeFromTv.setText(bean.getTypeText());
            if (bean.getIsNew()==1) {
                h.noticeTagIv.setVisibility(View.VISIBLE);
            } else {
                h.noticeTagIv.setVisibility(View.GONE);
            }
            h.noticeRootRl.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    h.noticeTagIv.setVisibility(View.GONE);
                    games.get(position).setIsNew(0);
                    showDialog(bean, position);
                }
            });
        }

        @Override
        public int getItemCount() {
            return games.size();
        }
    }

    private void showDialog(NotifiCationMain.NotificationListBean bean, final int position) {
        if (bean==null) {
            return;
        }

        if (!StringUtils.isEmpty(bean.getNoticeId()))
            MobileCodeUtils.taskReadNotifyTag(getContext(), bean.getNoticeId());

        if (bean.getRelateInfo()==null && bean.getJumpInfo()!=null) {
            IntentUtil.getInstance().intentTo(getActivity(), bean.getJumpInfo());
            return;
        }
        if (bean==null || bean.getRelateInfo()==null || bean.getRelateInfo().getFuncData()==null) {
            return;
        }
        final NotifiCationMain.NotificationListBean.RelateInfoBean.FuncDataBean funcDataBean
                = bean.getRelateInfo().getFuncData();

        final MessageDialog messageDialog = new MessageDialog(getActivity());
        messageDialog.show();
        if (funcDataBean.getRelateInfo()!=null) {
            messageDialog.setModelLl(funcDataBean.getRelateInfo().getIcon(), funcDataBean.getRelateInfo().getText());
        }
        messageDialog.setTitle(getResources().getString(R.string.message_dialog_title_str));
        messageDialog.showTopCancle();
        messageDialog.setMsg(funcDataBean.getMsg());
        messageDialog.setCancelBtn(funcDataBean.getCancelLabel(), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                messageDialog.dismiss();
                if (funcDataBean.getCancelFunc().equals("open")) {
                    IntentUtil.getInstance().intentTo(getActivity(), funcDataBean.getCancelData());
                } else if (funcDataBean.getCancelFunc().equals("ajaxRequest")) {
                    postAsynHttp(funcDataBean.getCancelData().getUrl(), funcDataBean.getCancelData().getPostData()
                            , funcDataBean.getCancelData().getFunc(), position);
                }
            }
        });
        messageDialog.setOkBtn(funcDataBean.getEnterLabel(), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                messageDialog.dismiss();
                if (funcDataBean.getEnterFunc().equals("open")) {
                    IntentUtil.getInstance().intentTo(getActivity(), funcDataBean.getEnterData());
                } else if (funcDataBean.getEnterFunc().equals("ajaxRequest")) {
                    postAsynHttp(funcDataBean.getCancelData().getUrl(), funcDataBean.getCancelData().getPostData()
                            , funcDataBean.getCancelData().getFunc(), position);
                }
            }
        });
    }

    private void postAsynHttp(String url, String postData, final String func, final int position) {
        try {
            if (StringUtils.isEmpty(url))
                return;

            FormBody.Builder builder = new FormBody.Builder();
            if (!StringUtils.isEmpty(postData)) {
                String[] dataL = postData.split("&");
                for (int i=0;i<dataL.length;i++) {
                    String[] dataK = dataL[i].split("=");
                    if (dataK.length==2) {
                        builder.add(dataK[0], dataK[1]);
                    }
                }
            }
            OkHttpClient mOkHttpClient=new OkHttpClient();
            Request request = new Request.Builder()
                    .url(url)
                    .post(builder.build())
                    .build();
            Call call = mOkHttpClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String str = response.body().string();
                    ((NoticeActivity)getActivity()).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (games!=null && games.size()>0 && position<games.size()) {
                                games.get(position).setIsNew(0);
                                if (func.equals("delete")) {
                                    adapter.removeItemByPosition(position);
                                    showToast("删除成功！");
                                }
                            }
                        }
                    });
                }

            });
        } catch (Exception e) {
            LogUtils.e("tbl>>>e:"+e.getMessage());
        }
    }

}
